package com.xand.bt.terminal.main;

import java.util.ArrayList;
import java.util.List;

import com.xand.bt.terminal.common.api.MarketConnector;
import com.xand.bt.terminal.common.api.MarketDepthUpdate;
import com.xand.bt.terminal.market.MarketStore;

public class MarketInfoUpdaterThread implements Runnable {
	
	private static final int SLEEP_INTERVAL = 500;
	
	private Thread thread;
	
	private boolean running = false;
	
	private List<MarketConnector> connectors;
	
	private MarketStore marketStore;
	
	public MarketInfoUpdaterThread(MarketStore marketStore) {
		this.thread = new Thread(this, "MARKET_INFO_UPDATER");
		
		this.connectors = new ArrayList<MarketConnector>();
		
		this.marketStore = marketStore;
	}
	
	public void start() {
		this.thread.start();
		
		this.running = true;
	}
	
	public void addMarketConnector(MarketConnector connector) {
		this.connectors.add(connector);
	}
	
	public void run() {
		
		while(this.running) {
			
			// poll every connector for updates
			synchronized(this.connectors) {
				
				for(MarketConnector connector : connectors) {
					
					List<MarketDepthUpdate> updates = new ArrayList<MarketDepthUpdate>();
					connector.updateMarketDepth(updates);
					
					this.processUpdates(connector.getClass(), updates);
					
				}
				
			}
			
			try {
				Thread.sleep(SLEEP_INTERVAL);
			} catch(InterruptedException e) {
				throw new RuntimeException(e);
			}
		}
		
	}
	
	public void stop() {
		this.running = false;
	}
	
	private void processUpdates(Class clazz, List<MarketDepthUpdate> updates) {
		
		String className = clazz.getCanonicalName();
		
		for(MarketDepthUpdate update : updates) {
			
			if(update.getReference().equals("btc_usd")) {
				this.marketStore.processMarketDepthUpdate(className, update);
				System.out.println(update.toString());
			}
			
		}
		
	}
}
